package com.postracker.postracker;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Iterator;

import au.com.bytecode.opencsv.CSVReader;

import com.postracker.postracker.db.DataBase;
import com.postracker.postracker.db.DataBaseFactory;
import com.postracker.postracker.db.InsertRow;
import com.postracker.postracker.io.TextRowFile;

public class App {

	private static DataBase db;

	public static void main(String[] args) throws SQLException, IOException {
		db = DataBaseFactory.createNewSqliteDB();
		db.openConnection();
		initializeDB();
		URL resource = App.class.getResource("/user.csv");
		File file = new File(resource.getPath());
		String filePath = file.getAbsolutePath();

		CSVReader reader = new CSVReader(new FileReader(filePath));
		Iterator<String[]> iterator = reader.readAll().iterator();

		InsertRow insertRow = new InsertRow("user", iterator.next());

		while (iterator.hasNext()) {
			insertRow.setSortedValues(iterator.next());
			String insertSql = insertRow.getInsertStatement();
			db.executeStmt(insertSql);
		}
		db.closeConnection();
		reader.close();

	}

	private static void initializeDB() throws SQLException, IOException {
		TextRowFile file = new TextRowFile("initDatabase.sql");
		for (String statement : file.getAllLines()) {
			db.executeStmt(statement);
		}
	}

}
